use std::fs::File;
use std::fs::OpenOptions;
use std::io::prelude::*;
use std::io::BufReader;
use rand::Rng;

// 文件读写
fn main() {
    // vector 只能储存相同类型的值
    let v = vec![String::from("sefghjhgfsdfghfdsa"), String::from("张赛道好玩idhwdjodo")];
    write_file(String::from("/tmp/dst"), &v);

    let appendV = vec![String::from("寄到德金哦阿斯"), String::from("个人待规划基数")];
    write_append_file(String::from("/tmp/dst"), &appendV);

    read_file_line(String::from("/tmp/dst"));
    read_file_all(String::from("/tmp/dst"));
    read_file_bytes(String::from("/tmp/dst"));
}

fn write_file(file: String, bodys: &Vec<String>){
    println!("写入文件");

    let mut f = File::create(file).unwrap();

    for body in bodys {
        f.write(body.as_bytes()).unwrap();
        f.write("\n".as_bytes()).unwrap();
    }
}

fn write_append_file(file: String, bodys: &Vec<String>){
    println!("追加文件文件");

    let mut f = OpenOptions::new().create(true).append(true)
        .open(file).unwrap();

    for body in bodys {
        f.write(body.as_bytes()).unwrap();
        f.write("\n".as_bytes()).unwrap();
    }
}

fn read_file_line(file: String){
    println!("===========================================");
    println!("逐行读取");
    println!("===========================================");

    let f = File::open(file).unwrap();

    let reader = BufReader::new(f);
    for line in reader.lines() {
        // line 是 std::result::Result<std::string::String, std::io::Error> 类型
        // line 不包含换行符
        let line = line.unwrap();
        println!("line: {}", line);
    }
}

fn read_file_all(file: String){
    println!("===========================================");
    println!("读取全部");
    println!("===========================================");

    let mut f = File::open(file).unwrap();

    let mut buf = String::new();
    f.read_to_string(&mut buf).unwrap();
    println!("ALL: {}", buf);
}

fn read_file_bytes(file: String){
    println!("===========================================");
    println!("按字节读取");
    println!("===========================================");

    let mut f = File::open(file).unwrap();
    let mut buf = vec![0; 8];
    let n = f.read(&mut buf[..]).unwrap();
    println!("{:?}", &buf[..n]);
}

// 生成随机unicode字符串
fn get_random_string(len: usize) -> String {
    rand::thread_rng()
        .sample_iter::<char, _>(rand::distributions::Standard)
        .take(len)
        .collect()
}

// 生成随机数字
fn get_random_num() -> i32 {
    rand::thread_rng().gen_range(1..=100)
}